package com.dj.mingkong.admin.biz.service.system.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dj.mingkong.admin.biz.controller.system.vo.request.RoleAddVo;
import com.dj.mingkong.admin.biz.controller.system.vo.request.RoleQueryVo;
import com.dj.mingkong.admin.biz.controller.system.vo.request.RoleUpdateVo;
import com.dj.mingkong.admin.biz.controller.system.vo.response.RoleVo;
import com.dj.mingkong.admin.biz.repository.database.system.RoleRepository;
import com.dj.mingkong.admin.biz.service.system.RoleService;
import com.dj.mingkong.common.enums.StatusEnum;
import com.dj.mingkong.common.infrastructure.base.dto.delete.DeleteVo;
import com.dj.mingkong.common.infrastructure.base.dto.page.PageVo;
import com.dj.mingkong.common.infrastructure.eo.database.system.RoleEo;
import com.dj.mingkong.common.util.SmartBeanCopy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色服务实现类
 *
 * @author zenglonghui
 * @date: 2022/8/15 15:39
 */
@Slf4j
@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleRepository roleRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(RoleAddVo addVo) {
        final RoleEo roleEo = SmartBeanCopy.copy(addVo, RoleEo.class);
        roleRepository.save(roleEo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateById(RoleUpdateVo updateVo) {
        final RoleEo roleEo = SmartBeanCopy.copy(updateVo, RoleEo.class);
        roleRepository.updateById(roleEo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(DeleteVo deleteVo) {
        roleRepository.deleteById(deleteVo.getId());
    }

    @Override
    public PageVo<RoleVo> pageByVo(RoleQueryVo queryVo) {
        final Page<RoleEo> roleEoPage = roleRepository.listPageByVo(queryVo);
        return SmartBeanCopy.copyPageVo(roleEoPage, RoleVo.class);
    }

    @Override
    public List<RoleVo> listAll() {
        final List<RoleEo> roleEos = roleRepository.list();
        final List<RoleVo> roleVos = SmartBeanCopy.copy(roleEos, RoleVo.class);
        setDisabled(roleVos);
        return roleVos;
    }

    private void setDisabled(List<RoleVo> roleVos) {
        if (CollectionUtils.isNotEmpty(roleVos)) {
            roleVos.forEach(roleVo ->
                    roleVo.setDisabled(StatusEnum.INVALID.equalsIntVal(roleVo.getStatus())));
        }
    }

}
